import plugin from '../../../lib/plugins/plugin.js';
import { chat } from '../model/deepseek/chat.js';
import fs from 'fs';
import YAML from 'yaml';
import puppeteer from "../../../lib/puppeteer/puppeteer.js";


let trss;
let workDir = process.cwd();
try {
  const packageJson = fs.readFileSync(`${workDir}/package.json`, 'utf8');
  let data = JSON.parse(packageJson);
  trss = data.name == 'trss' ? 0 : 1
} catch (error) {
  logger.error('Failed to read or parse package.json:', error);
}

export class DeepseekChatPlugin extends plugin {
  constructor() {
    super({
      name: 'fufu_chat',
      dsc: '',
      event: 'message',
      priority: 2000,
      rule: [
        {
          reg: '^#ds结束聊天$',
          fnc: 'endChat'
        },
        {
          reg: '^#ds(.*)',
          fnc: 'deepChat'
        },
        {
          reg: '^#获取聊天列表$',
          fnc: 'getChatList'
        },
        {
          reg: '^#删除聊天列表$',
          fnc: 'deleteChatList'
        },
        {
          reg: '^#切换聊天频道(.*)',
          fnc: 'getChatId'
        },
      ]
    }); 
  }

  async deepChat(e) {
    let data = YAML.parse(fs.readFileSync('./plugins/dsplugin-plugin/config/config.yaml', 'utf8'));
    let message = '';
    if (!e.msg.startsWith('#')) {
      message = e.msg.replace(/^\/ds/, '').trim();
    } else {
      message = e.msg.replace(/^#ds/, '').trim();
    }

    let chatContent = await chat(message, e.user_id);
    if (chatContent.code != 0) {
      return e.reply(chatContent.msg);
    }
    e.reply('目前seek服务器不稳定，请耐心等待', true, { recallMsg: 6 });
    if (data.shouldEnableImageCompose) {
      let data = {
        tplFile: './plugins/dsplugin-plugin/resources/html/chat.html',
        Group: e.group_id,
        QQ: e.user_id,
        chatmsg: chatContent.content.fullResponse,
        chatskao: chatContent.content.thinking,
        ChatQQ: (trss == 0) ? Bot.uin : './plugins/dsplugin-plugin/resources/img/tb.jpg' // 添加对trss的判断
      };
      let img = await puppeteer.screenshot("123", {
        ...data,
      });
      return e.reply(img);
    } else {
      let msg = (chatContent.content.thinking)
        ? `思考--------\n${chatContent.content.thinking}\n--------\n${chatContent.content.fullResponse}`
        : chatContent.content.fullResponse;
      return e.reply(msg);
    }
  }
}